import * as vscode from "vscode";
import { hasChinese, isExcluded } from "./utils/check";
import { getConfig } from "./utils/file";
import parseVue2 from "./vue2";
import { ILoggerType } from "./types";
import { batchTranslate } from "./utils/translate";

const commands = {
  /** 提取中文*/
  extract: "extension.code4x.extract",
  /**翻译 */
  translate: "extension.code4x.translate",
};

/**
 * 日志输出通道
 * @description 用于输出日志信息到 VSCode 输出面板
 */
const logChannel = vscode.window.createOutputChannel("i18n-tool", {
  log: true,
});

/**
 * 日志输出函数
 * @param msg 日志内容
 * @param type 日志类型，默认为 appendLine
 */
function logger(msg: string, type: ILoggerType = "info") {
  // 如果是debug模式，直接输出到控制台
  // return logChannel ? logChannel[type](msg) : console.log(msg);
  logChannel[type](msg);
}

function getWorkspaceRoot() {
  const workspaceFolders = vscode.workspace.workspaceFolders;
  if (!workspaceFolders) {
    vscode.window.showErrorMessage("未打开任何项目文件夹！");
    return;
  }
  const workspaceFolder = workspaceFolders[0];
  return workspaceFolder.uri.fsPath;
}

export function activate(context: vscode.ExtensionContext) {
  const extract = vscode.commands.registerCommand(
    commands.extract,
    async () => {
      logger(`开始提取中文`);
      const editor = vscode.window.activeTextEditor;
      // 如果没有打开编辑器，直接返回
      if (!editor) {
        return;
      }
      const workspaceRoot = getWorkspaceRoot();
      const CONFIG = getConfig(workspaceRoot);
      // 获取当前文档对象
      const { document } = editor;
      const { fileName } = document;
      // if (isExcluded(fileName, CONFIG.EXCLUDE)) {
      //   logger(`[Info] 文件被排除在外，结束提取：${fileName}`);
      //   return;
      // }

      // 获取当前文件内容
      const text = document.getText();
      if (hasChinese(text, CONFIG.CHINESE_REGEX)) {
        logger(`文件有中文，开始提取`);
        parseVue2({ filePath: fileName, CONFIG, logger });
        logger(`提取完毕`);
      } else {
        logger(`文件没有中文，结束提取`);
      }
      // 显示输出通道面板
      logChannel.show(true);
    }
  );
  const translate = vscode.commands.registerCommand(
    commands.translate,
    async () => {
      const workspaceRoot = getWorkspaceRoot();
      const CONFIG = getConfig(workspaceRoot);
      batchTranslate(CONFIG, logger);
    }
  );
  context.subscriptions.push(extract, translate);
}
